package com.bawei.home

import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import android.view.View.OnClickListener
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.base.RoutePath
import com.bawei.common.mvi.BaseMviFragment
import com.bawei.home.adapter.HomePageAdapter
import com.bawei.home.databinding.FragmentHomeBinding
import com.bawei.home.intent.HomeViewIntent
import com.bawei.home.state.HomeUiState
import com.bawei.home.vm.HomeViewModel
<<<<<<< HEAD

import com.bumptech.glide.Glide
=======


import com.bumptech.glide.Glide

>>>>>>> 4bd9ee2c4d9f0e81098ef6d1abae9f2eb7ec6c07
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint



/*
* 20250214 游戏鸿蒙-i视频-06-直播PUSHV1.1
* */


@AndroidEntryPoint
@Route(path = RoutePath.PATH_FRAGMENT_HOME)
class HomeFragment : BaseMviFragment<FragmentHomeBinding>() {


    private val mViewModel: HomeViewModel by activityViewModels()
    private val fragments = mutableListOf<HomeListFragment>()
    private lateinit var homePageAdapter: HomePageAdapter
    private var tabList = mutableListOf<SimpleTypeEntity>()
    private lateinit var mCountDownTimer: CountDownTimer

    private val searchHotWords = listOf("视频", "青年", "热门视频", "搞笑视频")


    private val handler = Handler(Looper.getMainLooper())
    private var secondsLeft = 5

    private val runnable = object : Runnable {
        override fun run() {
            if (secondsLeft > 0) {
                secondsLeft--
                handler.postDelayed(this, 1000)
            } else {
                mDataBinding.headHomeIv.visibility = View.VISIBLE
            }
        }
    }

    override fun getLayoutId(): Int = R.layout.fragment_home
    override fun onStart() {
        super.onStart()
        var repeatCount = 0
        val maxRepeats = 2
        handler.postDelayed(object : Runnable {
            override fun run() {
                if (repeatCount<maxRepeats){
                    // 执行操作
                    executeTask()
                    repeatCount++
                    // 再次延迟执行
                    handler.postDelayed(this, 5000)
                }
            }
        }, 5000)
    }
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return super.onCreateView(inflater, container, savedInstanceState)
    }

    private fun executeTask() {
        if (mDataBinding.notice.visibility==View.VISIBLE){
            mDataBinding.notice.visibility=View.GONE
        }else{
            mDataBinding.notice.visibility=View.VISIBLE
        }

    }

    override fun initViews() {
        //设置搜索热词
        mDataBinding.tvbSearch.setDatas(searchHotWords)
        mDataBinding.tvbSearch.setItemOnClickListener { hotKeyWords, _ ->
            jumpToSearchPage(hotKeyWords)
        }

        mDataBinding.ivMsg.setOnClickListener {
            jumpToMsgPage()
        }


        //测试
        mDataBinding.ivLogo.setOnClickListener {
            ARouter.getInstance().build(RoutePath.PATH_GOOD_PAGE).navigation()
        }

        homePageAdapter = HomePageAdapter(fragments, this@HomeFragment.childFragmentManager, lifecycle)
        mDataBinding.vp2Home.offscreenPageLimit = 1
        mDataBinding.vp2Home.adapter = homePageAdapter

        mDataBinding.notice.setOnClickListener{
            showToastMsg("123")
            ARouter.getInstance().build(RoutePath.PATH_LIVE_PAGE).navigation()
        }
//
//        //关联TabLayout与ViewPager2
        TabLayoutMediator(mDataBinding.tabTypeLayout, mDataBinding.vp2Home) { tab, position ->
            tab.text = tabList[position].typename
         }.attach()

        //设置VewPager2页面切换事件
        mDataBinding.vp2Home.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback(){
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                //存在Fragment还没有绑定到Activity中现象
                if (fragments[position].isAdded){
                    fragments[position].lazyLoadData()
                } else {
                    mDataBinding.vp2Home.postDelayed({
                        fragments[position].lazyLoadData()
                    }, 350)
                }
            }
        })


        Glide.with(requireActivity()).load(R.drawable.head).circleCrop().into(mDataBinding.headHomeIv)

        // 创建一个 CountDownTimer 实例
        mCountDownTimer = object : CountDownTimer(5000, 1000) {
            // 每过 1 秒调用一次该方法
            override fun onTick(millisUntilFinished: Long) {

            }

            // 倒计时结束时调用该方法
            override fun onFinish() {
                mDataBinding.headHomeIv.visibility = View.VISIBLE
            }
        }.start()

//        mDataBinding.headHomeIv.setOnClickListener {
//            showToastMsg("正在进入直播间。。。")
//            mDataBinding.headHomeIv.visibility = View.GONE
//        }

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 开始倒计时
        handler.post(runnable)
    }

    private fun jumpToSearchPage(keyWords: String){
        ARouter.getInstance().build(RoutePath.PATH_SEARCH_PAGE).withString("keyWords", keyWords).navigation()
    }

    private fun jumpToMsgPage(){
        ARouter.getInstance().build(RoutePath.PATH_MESSAGE_PAGE).navigation()
    }

    override suspend fun sendViewIntent() {
        mViewModel.channel.send(HomeViewIntent.LoadVideoType)
    }

    override suspend fun collectUiState() {
        mViewModel.uiState.collect{
            when(it){
                is HomeUiState.LoadSimpleTypeSuccess -> initTabFragment(it.list)
                is HomeUiState.LoadSimpleTypeFail -> showToastMsg(it.msg)
                else -> {}
            }
        }

    }

    private fun initTabFragment(list: List<SimpleTypeEntity>){
        if (list.isNotEmpty()){
            //添加推荐Tab
            tabList.add(SimpleTypeEntity("", 0, -1, 0, "", "推荐"))
            fragments.add(HomeListFragment.newInstance(-1, ""))
            //其他分类Tab
            list.forEach {
                tabList.add(it)
                fragments.add(HomeListFragment.newInstance(it.id, it.channelid))
            }
            //设置分类Tab
            tabList.forEach {
                mDataBinding.tabTypeLayout.addTab(mDataBinding.tabTypeLayout.newTab().setText(it.typename))
            }
            //通知页面更新
            homePageAdapter.notifyDataSetChanged()
        }
    }


}